/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pv1682010;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Set;
import java.util.TreeSet;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Isamaru
 */
public class Statistics {
    private DataSource dataSource;
    private Logger log=LoggerFactory.getLogger(CourseManager.class);

    public Statistics(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Statistics() {
        this(null);
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        log.debug("Data Source set to {}.", dataSource);
    }

    public NavigableSet<User> getAtLeastAttended(Course course, int atLeast) throws StatisticsException{
        NavigableSet<User> succeeded = null;
        try {
            //TODO: throwing SQLex!
            if (course == null) {
                throw new IllegalArgumentException("course cannot be null");
            }
            CourseManager courseManager = new CourseManager(dataSource);
            Map<User, Integer> users = new HashMap<User, Integer>();
            for (User user : courseManager.getEnrolled(course)) {
                users.put(user, 0);
            }
            Set<Event> events = courseManager.getEventsForCourse(course);
            for (Event event : events) {
                NavigableSet<User> usersOnCourse = courseManager.getAttendees(event);
                for (User user : usersOnCourse) {
                    users.put(user, users.get(user) + 1);
                }
            }
            succeeded = new TreeSet<User>();
            for (User user : users.keySet()) {
                if (users.get(user) >= atLeast) {
                    succeeded.add(user);
                }
            }
        } catch (SQLException ex) {
            throw new StatisticsException(ex);
        }
        return succeeded;
    }

    public NavigableSet<User> getMaxNonAttended(Course course, int max) throws StatisticsException {
        CourseManager courseManager = new CourseManager(dataSource);
        if (course == null) {
            throw new IllegalArgumentException("course cannot be null");
        }
        try {
            return getAtLeastAttended(course, courseManager.getEventsForCourse(course).size() - max);
        } catch (SQLException ex) {
            throw new StatisticsException(ex);
        }
    }
}
